package com.nzd.slsharing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.nzd.slsharing.dto.CommentDto;
import com.nzd.slsharing.dto.LikeDto;
import com.nzd.slsharing.dto.PostDto;
import com.nzd.slsharing.exception.CustomExpiredException;
import com.nzd.slsharing.pojo.*;
import com.nzd.slsharing.service.*;
import com.nzd.slsharing.util.Result;
import javafx.geometry.Pos;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//板块管理控制器(负责管理公共板块中的公共业务)
@RestController
@RequestMapping("/api/plateManagement")
public class PlateManagementController {
    //生活分享
    @Resource
    private LifeSharingService lifeSharingService;
    //学习交流
    @Resource
    private LearningExchangService learningExchangService;
    //作者
    @Resource
    private UserService userService;
    //点赞
    @Resource
    private LikeService likeService;
    //评论
    @Resource
    private CommentService commentService;
   //关注
   @Resource
   private StarService starService;

    @GetMapping("/findByIdAndType")
    public Result findPage(@RequestParam(required = false, defaultValue = "") Integer postId,
                           @RequestParam(required = false, defaultValue = "") Integer commentType) {

        // 检查参数有效性
        if (postId == null || postId <= 0 || commentType == null || (commentType != 1 && commentType != 2)) {
            return Result.fail("Invalid parameters");
        }

        // 根据帖子类型获取帖子信息
        PostDto postDto = new PostDto();

        // 根据类型获取帖子对象
        Object post = getPostByType(postId, commentType);
        if (post == null) {
            return Result.fail("Post not found");
        }

        // 设置 postDto 的公共属性
        setPostDto(post, postDto);

        return Result.ok(postDto);
    }

    // 根据帖子id和类型获取相应的帖子对象
    private Object getPostByType(Integer postId, Integer commentType) {
        if (commentType == 1) {
            return lifeSharingService.getById(postId);
        } else if (commentType == 2) {
            return learningExchangService.getById(postId);
        }
        return null;
    }

    // 设置 PostDto 的公共属性
    private void setPostDto(Object post, PostDto postDto) {
        if (post instanceof LifeSharing) {
            LifeSharing lifeSharing = (LifeSharing) post;
            User user = userService.getUserByStudentId(lifeSharing.getAuthor());
            postDto.setAuthor(user.getStudentId());
            postDto.setPostName(lifeSharing.getName());
            postDto.setAuthorName(user.getUsername());
            postDto.setTitle(lifeSharing.getName());
            postDto.setContent(lifeSharing.getContent());
            postDto.setPostDate(lifeSharing.getCreateTime());
            postDto.setPostImg(lifeSharing.getPostImage());
            postDto.setPostId(lifeSharing.getId());
            postDto.setNumberLikes(lifeSharing.getNumberLikes());
            postDto.setPostType(lifeSharing.getType());
        } else if (post instanceof LearningExchange) {
            LearningExchange learningExchange = (LearningExchange) post;
            System.out.println("当前为用");
            System.out.println(learningExchange.toString());
            User user = userService.getUserByStudentId(learningExchange.getAuthor());
            System.out.println("1");
            System.out.println(user.toString());
            postDto.setAuthor(user.getStudentId());
            postDto.setPostName(learningExchange.getName());
            postDto.setAuthorName(user.getUsername());
            postDto.setTitle(learningExchange.getName());
            postDto.setContent(learningExchange.getContent());
            postDto.setPostDate(learningExchange.getCreateTime());
            postDto.setPostImg(learningExchange.getPostImage());
            postDto.setPostId(learningExchange.getId());
            postDto.setNumberLikes(learningExchange.getNumberLikes());
            postDto.setPostType(learningExchange.getType());
            System.out.println("设置为后"+postDto.toString());
        }
    }

    @GetMapping("/isLike")
    public Result isLike(
            @RequestParam(required = false, defaultValue = "") String studentId,
            @RequestParam(required = false, defaultValue = "") Integer postId,
            @RequestParam(required = false, defaultValue = "") Integer postType) {

        // 判断用户id是否为空
        if (studentId == null || studentId.equals("")) {
            return Result.fail("用户id为空！");
        }

        // 查询用户是否存在
        User user = userService.getUserByStudentId(studentId);
        if (user == null) {
            return Result.fail("没有此用户！请确认用户是否存在。");
        }

        // 查询用户是否已经点赞
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("like_user_id", studentId)
                .eq("post_id", postId)
                .eq("post_type", postType);

        Like like = likeService.getOne(queryWrapper);

        // false为未点赞，true为已点赞
        boolean isLiked = (like != null);

        return Result.ok(isLiked);
    }

    //用户点赞
    @PostMapping("/userlikes")
    public Result userlikes(@RequestBody LikeDto likeDto) {

        System.out.println(likeDto.toString());
        // 参数校验
        if (likeDto.getUserId().isEmpty() || likeDto.getPostId() == null || likeDto.getPostType() == null) {
            return Result.fail("Invalid parameters");
        }

        // 查询用户是否存在
        User user = userService.getUserByStudentId(likeDto.getUserId());
        if (user == null) {
            return Result.fail("User not found");
        }

        // 点赞
        Like like = new Like();
        like.setPostId(likeDto.getPostId());
        like.setPostType(likeDto.getPostType());
        like.setLikeUserId(likeDto.getUserId());
        like.setLikeTime(new Date());
        like.setLikeUserName(user.getUsername());

        // 增加对应帖子的点赞数量
        Object post = getPostByType(likeDto.getPostId(), likeDto.getPostType());

        if (post == null) {
            return Result.fail("Post not found");
        }

        if(post instanceof LifeSharing){
            LifeSharing lifeSharing = (LifeSharing) post;
            System.out.println(lifeSharing.toString());
            lifeSharing.setNumberLikes(lifeSharing.getNumberLikes()+1);
            lifeSharingService.updateById(lifeSharing);
        }else if(post instanceof LearningExchange){
           LearningExchange learningExchange = (LearningExchange) post;
            System.out.println(learningExchange.toString());
            learningExchange.setNumberLikes(learningExchange.getNumberLikes()+1);
            learningExchangService.updateById(learningExchange);
        }
        return Result.ok(likeService.save(like));
    }

    //取消点赞
    @PostMapping("/userNolikes")
    public Result userNolikes(@RequestBody LikeDto likeDto) {

        // 参数校验
        if (likeDto.getUserId().isEmpty() || likeDto.getPostId() == null || likeDto.getPostType() == null) {
            return Result.fail("Invalid parameters");
        }

        // 查询用户是否存在
        User user = userService.getUserByStudentId(likeDto.getUserId());
        if (user == null) {
            return Result.fail("User not found");
        }

        // 取消点赞
        QueryWrapper queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("like_user_id", likeDto.getUserId());
        queryWrapper.eq("post_id", likeDto.getPostId());
        queryWrapper.eq("post_type", likeDto.getPostType());


        // 减少对应帖子的点赞数量
        Object post = getPostByType(likeDto.getPostId(), likeDto.getPostType());

        if (post == null) {
            return Result.fail("Post not found");
        }

        if(post instanceof LifeSharing){
            LifeSharing lifeSharing = (LifeSharing) post;
            System.out.println(lifeSharing.toString());
            if(lifeSharing.getNumberLikes() !=0){
                lifeSharing.setNumberLikes(lifeSharing.getNumberLikes()-1);
                lifeSharingService.updateById(lifeSharing);
            }

        }else if(post instanceof LearningExchange){
            LearningExchange learningExchange = (LearningExchange) post;
            System.out.println(learningExchange.toString());
            if(learningExchange.getNumberLikes()!=0){
                learningExchange.setNumberLikes(learningExchange.getNumberLikes()-1);
                learningExchangService.updateById(learningExchange);
            }

        }
        return Result.ok(likeService.remove(queryWrapper));
    }


    //评论
    @PostMapping("/comment")
    public Result comment(@RequestBody CommentDto commentDto) {
        if(commentDto.getStudentId().isEmpty()||commentDto.getName().isEmpty()||commentDto.getPostId()==null|commentDto.getCommentType()==null||commentDto.getCommentContent().isEmpty()){
            return Result.fail("参数为空！");
        }

        //参数不为空则添加
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDto, comment);


        return Result.ok(commentService.save(comment));
    }

    //查询点赞数量
    @GetMapping("/likeNum")
    public Result likenum(@RequestParam String userid){
        QueryWrapper<Like> queryWrapper= new QueryWrapper();
        queryWrapper.eq("like_user_id",userid);
       Integer num=likeService.count(queryWrapper);

        return Result.ok(num);
    }

    //查询关注数量
    @GetMapping("/focusNum")
    public Result focusum(@RequestParam String userid){
        QueryWrapper<Star> queryWrapper= new QueryWrapper();
        queryWrapper.eq("user_id",userid);
        Integer num= starService.count(queryWrapper);
        System.out.println("这是关注数量"+num);
        return Result.ok(num);
    }

    //查询粉丝数量
    @GetMapping("/fansNum")
    public Result fansnum(@RequestParam String userid){
        QueryWrapper<Star> queryWrapper= new QueryWrapper();
        queryWrapper.eq("star_user_id",userid);
        Integer num= starService.count(queryWrapper);
        return Result.ok(num);
    }

    //查询我的点赞
    @GetMapping("/userlikelist")
    public Result userlikelist(@RequestParam String userid){
        QueryWrapper<Like> queryWrapper= new QueryWrapper();
        queryWrapper.eq("like_user_id",userid);
        List<Like> likes = likeService.list(queryWrapper);
        List<PostDto> postDtoList= new ArrayList<>();
        for(Like like:likes){
            if(like.getPostType()==1){
                PostDto postDto = new PostDto();
                LifeSharing lifeSharing=lifeSharingService.getById(like.getPostId());
               if(lifeSharing!=null){
                   //对象复制
                   BeanUtils.copyProperties(lifeSharing,postDto);
                   postDto.setPostId(lifeSharing.getId());
                   postDto.setTitle(lifeSharing.getName());
                   postDto.setPostType(lifeSharing.getType());
                   postDto.setPostImg(lifeSharing.getPostImage());
                   postDto.setPostDate(lifeSharing.getCreateTime());
                   postDtoList.add(postDto);
               }
            }else if(like.getPostType()==2){{
                PostDto postDto = new PostDto();
                LearningExchange learningExchange=learningExchangService.getById(like.getPostId());
                if(learningExchange!=null){
                    //对象复制
                    BeanUtils.copyProperties(learningExchange,postDto);
                    postDto.setPostId(learningExchange.getId());
                    postDto.setTitle(learningExchange.getName());
                    postDto.setPostType(learningExchange.getType());
                    postDto.setPostImg(learningExchange.getPostImage());
                    postDto.setPostDate(learningExchange.getCreateTime());
                    postDtoList.add(postDto);
                }

            }
            }
        }
        return Result.ok(postDtoList);
    }

    //查询我的关注
    @GetMapping("/userfocuslist")
    public Result userfocuslist(@RequestParam String userid){
        QueryWrapper<Star> queryWrapper= new QueryWrapper();
        queryWrapper.eq("user_id",userid);
        List<User> users=new ArrayList<>();
        List<Star> starlist=starService.list(queryWrapper);
        for (Star star:starlist){
            User user=userService.getUserByStudentId(star.getStarUserId());
            if(user!=null){
                user.setPassword(null);
                users.add(user);
            }
        }

        return Result.ok(users);
    }

    //查询我的关注
    @GetMapping("/userfanslist")
    public Result userfanslist(@RequestParam String userid){
        QueryWrapper<Star> queryWrapper= new QueryWrapper();
        queryWrapper.eq("star_user_id",userid);
        List<User> users=new ArrayList<>();
        List<Star> starlist=starService.list(queryWrapper);
        for (Star star:starlist){
            User user=userService.getUserByStudentId(star.getUserId());
            if(user!=null){
                user.setPassword(null);
                users.add(user);
            }
        }

        return Result.ok(users);
    }



    //搜索
    @GetMapping("/search")
    public Result search(@RequestParam(required = false, defaultValue = "") String searchText){
        //存放返回结果
        List<PostDto> postDtoList=new ArrayList<>();
        QueryWrapper<LifeSharing> lifeSharingQ= new QueryWrapper();
        QueryWrapper<LearningExchange> learningExchangeQ= new QueryWrapper();
        lifeSharingQ.like("name",searchText);
        learningExchangeQ.like("name",searchText);
        List<LifeSharing> lifeSharings=lifeSharingService.list(lifeSharingQ);
        List<LearningExchange> learningExchanges=learningExchangService.list(learningExchangeQ);
        //组装返回结果
        for (LifeSharing lifeSharing:lifeSharings){
            PostDto postDto=new PostDto();
            //对象复制
            BeanUtils.copyProperties(lifeSharing,postDto);
            postDto.setPostId(lifeSharing.getId());
            postDto.setTitle(lifeSharing.getName());
            postDto.setPostType(lifeSharing.getType());
            postDto.setPostImg(lifeSharing.getPostImage());
            postDto.setPostDate(lifeSharing.getCreateTime());
            postDtoList.add(postDto);
        }
        for (LearningExchange learningExchange:learningExchanges){
            PostDto postDto=new PostDto();
            //对象复制
            BeanUtils.copyProperties(learningExchange,postDto);
            postDto.setPostId(learningExchange.getId());
            postDto.setTitle(learningExchange.getName());
            postDto.setPostType(learningExchange.getType());
            postDto.setPostImg(learningExchange.getPostImage());
            postDto.setPostDate(learningExchange.getCreateTime());
            postDtoList.add(postDto);
        }

        return Result.ok(postDtoList);
    }

    @GetMapping("/recommend")
    public Result recommend() {
        // 存放返回结果
        List<PostDto> postDtoList = new ArrayList<>();

        // 获取所有 LifeSharing 和 LearningExchange 数据
        List<LifeSharing> lifeSharings = lifeSharingService.list();
        List<LearningExchange> learningExchanges = learningExchangService.list();

        // 合并两个列表
        List<Object> allPosts = new ArrayList<>();
        allPosts.addAll(lifeSharings);
        allPosts.addAll(learningExchanges);

        // 按照 number_likes 降序排序
        allPosts.sort((a, b) -> {
            int likesA = 0;
            int likesB = 0;

            // 获取点赞数
            if (a instanceof LifeSharing) {
                likesA = ((LifeSharing) a).getNumberLikes();
            } else if (a instanceof LearningExchange) {
                likesA = ((LearningExchange) a).getNumberLikes();
            }

            if (b instanceof LifeSharing) {
                likesB = ((LifeSharing) b).getNumberLikes();
            } else if (b instanceof LearningExchange) {
                likesB = ((LearningExchange) b).getNumberLikes();
            }

            return Integer.compare(likesB, likesA); // 降序排列
        });

        // 取前三个
        List<Object> topPosts = allPosts.stream().limit(3).collect(Collectors.toList());

        // 组装返回结果
        for (Object post : topPosts) {
            PostDto postDto = new PostDto();
            String authorId = null;
            User user = null;

            if (post instanceof LifeSharing) {
                LifeSharing lifeSharing = (LifeSharing) post;
                authorId = lifeSharing.getAuthor();
                BeanUtils.copyProperties(lifeSharing, postDto);
                postDto.setPostId(lifeSharing.getId());
                postDto.setTitle(lifeSharing.getName());
                postDto.setPostType(lifeSharing.getType());
                postDto.setPostImg(lifeSharing.getPostImage());
                postDto.setPostDate(lifeSharing.getCreateTime());
            } else if (post instanceof LearningExchange) {
                LearningExchange learningExchange = (LearningExchange) post;
                authorId = learningExchange.getAuthor();
                BeanUtils.copyProperties(learningExchange, postDto);
                postDto.setPostId(learningExchange.getId());
                postDto.setTitle(learningExchange.getName());
                postDto.setPostType(learningExchange.getType());
                postDto.setPostImg(learningExchange.getPostImage());
                postDto.setPostDate(learningExchange.getCreateTime());
            }

            // 获取作者信息
            if (authorId != null) {
                user = userService.getUserByStudentId(authorId);
            }

            // 设置作者信息
            if (user != null) {
                postDto.setAuthorName(user.getUsername());
                postDto.setUserImg(user.getHeadSculpture());
            }

            postDtoList.add(postDto);
        }

        return Result.ok(postDtoList);
    }


}
